<template>
  <div>
    <el-steps :active="active" simple>
      <el-step title="验证身份" icon="el-icon-user-solid"></el-step>
      <el-step title="修改手机号" icon="el-icon-mobile-phone"></el-step>
      <el-step title="完成" icon="el-icon-circle-check"></el-step>
    </el-steps>
    <!-- 第一步 -->
    <div class="content_one" v-if="active === 1">
      <div class="title">为确认是您本人操作，请完成以下验证</div>
      <el-form ref="forgotForm" :model="sizeForm" size="mini" :rules="changeRiles" label-width="135px"
        label-position="left">
        <el-form-item label="已绑定的手机">
          <div class="phone">{{ showPhone }}</div>
        </el-form-item>
        <el-form-item prop="Verification" label="短信验证码">
          <el-tooltip class="item" effect="dark" content="请输入验证码" placement="right-end" popper-class="popperClass">
            <el-input v-model.trim="sizeForm.Verification" placeholder="请输入验证码" style="width: 30%;" />
          </el-tooltip>
          <el-button class="verify-btn" size="medium" @click="sendValidationOne">{{ validation }}</el-button>
        </el-form-item>
        <el-button type="primary" class="primary" @click="clickforgotOne">下一步</el-button>
      </el-form>
    </div>
    <!-- 第二步 -->
    <div class="content_one" v-if="active === 2">
      <el-form ref="TwoForm" :model="TwoForm" size="mini" :rules="changeRilesTwo" label-width="135px"
        label-position="left">

        <el-form-item label="原手机号码" key="2" style="margin-left:5px ;">
          <div class="phone">{{ showPhone }}</div>
        </el-form-item>

        <el-form-item prop="newPhone" label="新手机号号码" key="0">
          <el-tooltip class="item" effect="dark" content="请输入新手机号码" placement="right-end" popper-class="popperClass">
            <el-input v-model.trim="TwoForm.newPhone" placeholder="请输入新手机号码" style="width: 75%;"></el-input>
          </el-tooltip>
        </el-form-item>

        <el-form-item prop="Verification" label="短信验证码" key="1">
          <el-tooltip class="item" effect="dark" content="请输入验证码" placement="right-end" popper-class="popperClass">
            <el-input v-model.trim="TwoForm.Verification" placeholder="请输入验证码" style="width: 30%;" />
          </el-tooltip>
          <el-button class="verify-btn" size="medium" @click="sendValidationTwo">{{ twoValidation }}</el-button>
        </el-form-item>

        <el-button type="primary" class="primary" @click="clickforgotTwo">下一步</el-button>
      </el-form>
    </div>
    <!-- 第三步 -->
    <div class="content_three" v-if="active === 3">
      <div class="succsess"></div>
      <div>
        <h2>修改成功！</h2>
      </div>
      <el-button type="primary" class="primary" @click="complete">完成</el-button>
    </div>
  </div>
</template>

<script>
import {
  updataPhoneRequest,
  getVerificationCodeRequest,
  regVerificationCodeRequest,
} from '@/api/user'
export default {
  name: 'GenescloudUiChangePhone',
  props: {
    bindingPhone: {
      type: String,
      default: ''
    }
  },
  computed: {
    //手机号屏蔽
    showPhone() {
      let left = this.bindPhone.substring(0, 3)
      let right = this.bindPhone.substring(this.bindPhone.length - 3)
      return left + '****' + right
    },
  },
  data() {
    let validateNewPhone = (rule, value, callback) => {
      if (value == this.bindPhone) {
        callback(new Error("新手机号与原手机号一致，请查验后再修改"));
      } else {
        callback();
      }
    }
    return {
      active: 1,
      bindPhone: this.bindingPhone,
      //第一步
      sizeForm: {
        Verification: '',
      },
      timer: null,
      validation: '发送验证码',
      countdown: 60,
      changeRiles: {
        Verification: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { pattern: /^[0-9]{6}$/, message: '请输入6位验证码', trigger: ['change', 'blur'] }
        ]
      },
      //第二步
      TwoForm: {
        newPhone: '',
        Verification: '',
      },
      twoTimer: null,
      twoValidation: '发送验证码',
      twoCountdown: 60,
      changeRilesTwo: {
        newPhone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/, message: '请输入正确的手机号码', trigger: ['change', 'blur'] },
          { required: true, validator: validateNewPhone, trigger: ['change', 'blur'] },
        ],
        Verification: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { pattern: /^[0-9]{6}$/, message: '请输入6位验证码', trigger: ['change', 'blur'] }
        ]
      }
    };
  },
  methods: {
    async sendValidationOne() {
      if (!this.timer) {
        const res = await getVerificationCodeRequest(
          {
            mobilePhone: this.bindingPhone,
            validCodeTypeName: 'phone_change_old_phone'
          }
        )
        if (res.code !== 200) {
          return this.$message({
            message: res.message,
            type: 'warning'
          });
        } else {
          this.validation = `60s后重新发送`;
          this.timer = setInterval(() => {
            if (this.countdown > 0 && this.countdown <= 60) {
              this.countdown--;
              if (this.countdown !== 0) {
                this.validation = `${this.countdown}s后重新发送`;
              } else {
                clearInterval(this.timer);
                this.validation = "重新发送";
                this.countdown = 60;
                this.timer = null;
                this.codeDisabled = false;
              }
            }
          }, 1000)
        }
      }
    },
    //验证码校验
    sendValidationTwo() {
      if (!this.twoTimer) {
        this.$refs['TwoForm'].validateField(['newPhone'], async err => {
          if (!err) {
            try {
              const res = await getVerificationCodeRequest(
                {
                  mobilePhone: this.TwoForm.newPhone,
                  validCodeTypeName: 'phone_change_new_phone'
                }
              )
              if (res.code !== 200) {
                return this.$message({
                  message: res.message,
                  type: 'warning'
                });

              } else {
                this.twoValidation = `60s后重新发送`;
                this.twoTimer = setInterval(() => {
                  if (this.twoCountdown > 0 && this.twoCountdown <= 60) {
                    this.twoCountdown--;
                    if (this.twoCountdown !== 0) {
                      this.twoValidation = `${this.twoCountdown}s后重新发送`;
                    } else {
                      clearInterval(this.twoTimer);
                      this.twoValidation = "重新发送";
                      this.twoCountdown = 60;
                      this.twoTimer = null;
                      this.codeDisabled = false;
                    }
                  }
                }, 1000)
              }
            } catch (error) {
              this.$message.error('错误，请联系管理员！')
            }
          }
        })
      }
    },
    clickforgotOne() {
      this.$refs['forgotForm'].validateField(['Verification'], async err => {
        if (!err) {
          try {
            const res = await regVerificationCodeRequest(
              {
                mobilePhone: this.bindPhone,
                validCode: this.sizeForm.Verification,
                validCodeTypeName: 'phone_change_old_phone'
              }
            )
            if (res.code !== 200) return this.$message.error(res.message)
            this.active = 2
          } catch (error) {
            this.$message.error('错误，请联系管理员！')
          }
        }
      })
    },
    clickforgotTwo() {
      this.$refs['TwoForm'].validate(async validate => {
        if (validate) {
          try {
            const res = await updataPhoneRequest({
              newMobilePhone: this.TwoForm.newPhone,
              newPhoneValidCode: this.TwoForm.Verification,
              oldMobilePhone: this.bindingPhone,
              oldPhoneValidCode: this.sizeForm.Verification
            })
            if (res.code !== 200) return this.$message.error(res.message)
            this.clear()
            this.active = 3
          } catch (error) {
            this.$message.error('系统错误，请联系管理员！')
          }
        }
      })
    },
    complete() {
      this.active = 1
      this.clear()
      this.$emit('complete', 'phone')
    },
    clear() {
      this.active = 1
      this.sizeForm = {
        Verification: ''
      }
      clearInterval(this.timer)
      this.timer = null
      this.validation = '发送验证码'
      this.countdown = 60
      this.sizeForm = {
        newPhone: '',
        Verification: ''
      }
      clearInterval(this.twoTimer)
      this.twoTimer = null
      this.twoValidation = '发送验证码'
      this.twoCountdown = 60
      if (this.$refs.forgotForm) this.$refs.forgotForm.resetFields()
      if (this.$refs.TwoForm) this.$refs.TwoForm.resetFields()
    }
  },
};
</script>

<style lang="scss" scoped>
.content_one {
  padding: 15px 150px;
  font-size: 15px;

  .title {
    margin-bottom: 25px;
  }

  ::v-deep .el-form-item--mini .el-form-item__label {
    font-weight: 400;

    &::before {
      content: ''
    }
  }

  ::v-deep .el-input--mini .el-input__inner {
    border-radius: 5px;
    height: 36px;
  }

  .verify-btn {
    float: right;
    margin-right: 28%;
    border-radius: 6px;
  }

  .primary {
    margin-left: 135px;
    border-radius: 5px
  }
}

.content_three {
  display: flex;
  flex-direction: column;
  align-items: center;

  .succsess {
    width: 100px;
    height: 100px;
    background: url(../../../../assets/success.png) no-repeat;
    background-size: 100px;
    margin: 12px 0;
  }

  h2 {
    padding-left: 15px;
  }

  .primary {
    border-radius: 5px
  }
}
</style>